package common

import (
	"github.com/gin-gonic/gin"
)

var ErrorCode = map[int]map[string]interface{}{
	10: {"desc": "没有该上游!", "status": 404},
	11: {"desc": "系统繁忙, 请稍后再试!", "status": 408},
}

type ServiceError struct {
	Errno  int    `json:"errno"`
	Errmsg string `json:"errmsg"`
	SysErr error  `json:"-"`
}

// BadRequst 自定义错误对象
type BadRequst struct {
	UpStream   string      `json:"upstream"`
	Desc       string      `json:"desc"`
	StatusCode int         `json:"status_code"`
	Detail     interface{} `json:"detail"`
}

func NewBadRequst(resource string, errorCode int, kwargs interface{}) *BadRequst {
	errorInfo := ErrorCode[errorCode]
	return &BadRequst{UpStream: resource, Desc: errorInfo["desc"].(string), StatusCode: errorInfo["status"].(int),
		Detail: kwargs}
}

func OtherError(e string) *BadRequst {
	return &BadRequst{UpStream: "default", Desc: "接口错误", StatusCode: 500,
		Detail: e}
}

func ErrHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				var Err *BadRequst
				if e, ok := err.(*BadRequst); ok {
					Err = e
				} else if e, ok := err.(error); ok {
					Err = OtherError(e.Error())
				}
				// 记录一个错误的日志
				c.JSON(Err.StatusCode, Err)
				return
			}
		}()
		c.Next()
	}
}
